import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, Select, Switch, message, Popconfirm, Card, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { api } from '../utils/api';

const { Option } = Select;

interface Certificate {
  id: number;
  user_id: number;
  username: string;
  exam_id: number;
  exam_title: string;
  score: number;
  is_valid: boolean;
  created_at: string;
  expire_at: string;
}

const CertificateManagement: React.FC = () => {
  const [certificates, setCertificates] = useState<Certificate[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCertificate, setEditingCertificate] = useState<Certificate | null>(null);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  useEffect(() => {
    fetchCertificates();
  }, [pagination.current, pagination.pageSize]);

  const fetchCertificates = async () => {
    try {
      setLoading(true);
      const response = await api.get('/certificates/admin/', {
        params: {
          page: pagination.current,
          per_page: pagination.pageSize
        }
      });
      if (response.data.success) {
        setCertificates(response.data.data.items);
        setPagination(prev => ({ ...prev, total: response.data.data.total }));
      }
    } catch (error) {
      message.error('获取证书列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (record: Certificate) => {
    setEditingCertificate(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await api.delete(`/certificates/admin/${id}`);
      message.success('删除成功');
      fetchCertificates();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingCertificate) {
        await api.put(`/certificates/admin/${editingCertificate.id}`, values);
        message.success('更新成功');
      } else {
        await api.post('/certificates/admin/', values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchCertificates();
    } catch (error) {
      message.error(editingCertificate ? '更新失败' : '创建失败');
    }
  };

  const columns = [
    {
      title: '证书ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '用户',
      dataIndex: 'username',
      key: 'username',
      width: 120
    },
    {
      title: '考试',
      dataIndex: 'exam_title',
      key: 'exam_title',
      width: 180
    },
    {
      title: '分数',
      dataIndex: 'score',
      key: 'score',
      width: 80
    },
    {
      title: '状态',
      dataIndex: 'is_valid',
      key: 'is_valid',
      width: 80,
      render: (valid: boolean) => (
        <Tag color={valid ? 'green' : 'red'}>{valid ? '有效' : '无效'}</Tag>
      )
    },
    {
      title: '发放时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150
    },
    {
      title: '到期时间',
      dataIndex: 'expire_at',
      key: 'expire_at',
      width: 150
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: Certificate) => (
        <Space size="small">
          <Button type="link" icon={<EyeOutlined />} onClick={() => Modal.info({ title: '证书详情', content: JSON.stringify(record, null, 2) })}>详情</Button>
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>编辑</Button>
          <Popconfirm title="确定要删除该证书吗？" onConfirm={() => handleDelete(record.id)} okText="确定" cancelText="取消">
            <Button type="link" danger icon={<DeleteOutlined />}>删除</Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card title="证书管理" extra={<Button type="primary" icon={<PlusOutlined />} onClick={() => { setEditingCertificate(null); form.resetFields(); setModalVisible(true); }}>新建证书</Button>}>
        <Table
          columns={columns}
          dataSource={certificates}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
          }}
          onChange={(pagination) => {
            setPagination(prev => ({ ...prev, current: pagination.current || 1, pageSize: pagination.pageSize || 10 }));
          }}
        />
      </Card>
      <Modal
        title={editingCertificate ? '编辑证书' : '新建证书'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={500}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item name="user_id" label="用户ID" rules={[{ required: true, message: '请输入用户ID' }]}> <Input /> </Form.Item>
          <Form.Item name="exam_id" label="考试ID" rules={[{ required: true, message: '请输入考试ID' }]}> <Input /> </Form.Item>
          <Form.Item name="score" label="分数" rules={[{ required: true, message: '请输入分数' }]}> <Input /> </Form.Item>
          <Form.Item name="is_valid" label="有效状态" valuePropName="checked"> <Switch checkedChildren="有效" unCheckedChildren="无效" /> </Form.Item>
          <Form.Item name="expire_at" label="到期时间"> <Input placeholder="YYYY-MM-DD" /> </Form.Item>
          <Form.Item> <Space> <Button type="primary" htmlType="submit">{editingCertificate ? '更新' : '创建'}</Button> <Button onClick={() => setModalVisible(false)}>取消</Button> </Space> </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CertificateManagement; 